/*
 * Copyright (C) 2008 Universidade Federal de Campina Grande
 *  
 * This file is part of OurGrid. 
 *
 * OurGrid is free software: you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free 
 * Software Foundation, either version 3 of the License, or (at your option) 
 * any later version. 
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT 
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
 * for more details. 
 * 
 * You should have received a copy of the GNU Lesser General Public License 
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package org.ourgrid.peer.ui.async.gui;

import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Collection;
import java.util.Collections;

import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import org.ourgrid.common.interfaces.to.UserInfo;
import org.ourgrid.peer.ui.async.client.PeerAsyncInitializer;

/**
 * It represents a panel where it is possible to view the status of the peer
 * users.
 */
public class PeerUserTablePanel extends javax.swing.JPanel {
    
	private static final long serialVersionUID = 1L;
	private PeerUserTableModel model;
	
	/** Creates new form PeerUserTablePanel */
    public PeerUserTablePanel() {
        initComponents();
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        tableScrollPane = new javax.swing.JScrollPane();
        peerUserTable = new javax.swing.JTable();

        peerUserTable.setModel(getTableModel());
        tableScrollPane.setViewportView(peerUserTable);
       
        peerUserTable.addMouseListener(new MouseAdapter() {
        	@Override
        	public void mouseClicked(MouseEvent e) {
        		if (peerUserTable.getSelectedColumn() == PeerUserTableModel.DELETE_COLUMN) {
        			deleteTableRow(peerUserTable.getSelectedRow());
        		}
        	}
        	
        	@Override
        	public void mouseEntered(MouseEvent e) {
        		if (peerUserTable.getSelectedColumn() == PeerUserTableModel.STATUS_COLUMN) {
        			ImageIcon icon = (ImageIcon) peerUserTable.getValueAt(peerUserTable.getSelectedRow(), peerUserTable.getSelectedColumn());
        			peerUserTable.setToolTipText(icon.getDescription());
        		}
        	}
        });
        
        BorderLayout bLayout = new BorderLayout();
        this.setLayout(bLayout);
        add(tableScrollPane, BorderLayout.CENTER);
        
        Box box = Box.createHorizontalBox();
        box.add(new JLabel("ONLINE   ", new ImageIcon(PeerUserTableModel.USER_ONLINE_IMAGE_PATH, "ONLINE"), JLabel.LEFT));
        box.add(new JLabel("OFFLINE   ", new ImageIcon(PeerUserTableModel.USER_OFFLINE_IMAGE_PATH, "OFFLINE"), JLabel.LEFT));
        
        add(box, BorderLayout.SOUTH);
       
        /*org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(tableScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(tableScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 276, Short.MAX_VALUE)
                .addContainerGap())
        );*/
    }// </editor-fold>//GEN-END:initComponents
    
    /**
     * Removes the specified row of this table.
     * @param selectedRow The row to be removed.
     */
    private void deleteTableRow(int selectedRow) {
    	String user = (String) getTableModel().getValueAt(selectedRow, PeerUserTableModel.USER_COLUMN);
    	String server = (String) getTableModel().getValueAt(selectedRow, PeerUserTableModel.SERVER_COLUMN);
    	
//    	getTableModel().removeRow(selectedRow);
    	
    	/*List<WorkerSpec> specs = new LinkedList<WorkerSpec>();
    	for (WorkerInfo workerInfo : data) {
			specs.add(workerInfo.getWorkerSpec());
		}*/
    	
    	int confirmDeletion = JOptionPane.showConfirmDialog(null, "Delete user [" + user + "@" + server + "] ?", 
    			"Delete user", JOptionPane.YES_NO_OPTION);
    	
    	if (confirmDeletion == JOptionPane.YES_OPTION) {
    		deletePeerUser(user, server);
//    		getTableModel().fireTableRowsDeleted(selectedRow, selectedRow);
    	}
	}
    
    /**
     * Remove a user from a Peer.
     * @param user User
     * @param server Server
     */
    private void deletePeerUser(String user, String server) {
		PeerAsyncInitializer.getInstance().getComponentClient().removeUser(user + "@" + server);
	}
    
    /**
     * Returns the table that displays the status of the peer
     * users.
     * @return The table that displays the status of the peer
     * users.
     */
    private PeerUserTableModel getTableModel() {
    	if (model == null) {
    		model = new PeerUserTableModel();
    	}
        return model;
    }
    
    /**
     * Defines the informations about the peer users.
     * @param data The informations about the peer users.
     */
    public void setTableModelData(Collection<UserInfo> data) {
    	model.setData(data); 	
   
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable peerUserTable;
    private javax.swing.JScrollPane tableScrollPane;
    // End of variables declaration//GEN-END:variables

	public void peerStopped() {
		setTableModelData(Collections.<UserInfo>emptyList());		
	}
    
}
